package utils

import (
	"bufio"
	"encoding/json"
	"fmt"
	"net"
	"os"
	"strconv"
	"strings"
	"syscall"
	"time"
)

func ProcessExistsFromFile(pidFile string) bool {
	data, err := os.ReadFile(pidFile)
	if err != nil {
		return false
	}

	pidStr := strings.TrimSpace(string(data))
	pid, err := strconv.Atoi(pidStr)
	if err != nil {
		return false
	}

	err = syscall.Kill(pid, 0)
	return err == nil || err == syscall.EPERM
}

func readRequestFromConn(c net.Conn) (req Requests, err error) {
	reader := bufio.NewReader(c)
	data, err := reader.ReadString('\n')
	if err != nil {
		return
	}
	data = strings.TrimRight(data, "\r\n")
	err = json.Unmarshal([]byte(data), &req)
	if err != nil {
		return
	}
	return req, nil
}

func SpinnerWaiting() {
	for {
		for _, r := range `-\|/` {
			fmt.Printf("\rwaiting %c", r)
			time.Sleep(100 * time.Millisecond)
		}
	}
}
